import React, {Component} from 'react';
import {
    StyleSheet, 
    View,
    Animated,
    TouchableOpacity,
    Image,
    Text,
    DeviceEventEmitter,
    SafeAreaView,
} from 'react-native';
import ScrollableTabView, { DefaultTabBar } from 'react-native-scrollable-tab-view';

import { getPixel, getScreenWidth, getScreenHeight } from '../common/common';
import BaseComponent from '../component/BaseComponent'
import HeaderBarWhite from '../component/HeaderBarWhite';
import AssetList from '../component/AssetList';
import AssetInit from '../component/AssetInit';
import AssetInfoSupplement from '../component/AssetInfoSupplement';
import AssetMove from '../component/AssetMove';
import InfraredModule from '../component/Infrared';
import {NavigationEvents} from 'react-navigation';
import DeviceInfo from 'react-native-device-info';

let currenTab = 0;
let that = {};

export default class Asset extends BaseComponent {

    constructor(props){
        super(props);
        this.state={
            fadeAnim: new Animated.Value(-(getScreenWidth() / 2)),    //-(getScreenWidth() / 2)
            tab: 0,
            keyWord: '',
        }
        that = this;
    }

    componentDidMount() {

        const { params } = this.props.navigation.state;
        const tab = params ? params.tab : 0; 
        const keyWord = params ? params.keyWord : ''; 

        this.setState({
            tab: tab,
            keyWord: keyWord,
        });
    }

    componentWillUnmount() {
        if(DeviceInfo.getDeviceId() === 'rk30sdk'){
            if(InfraredModule.getState() === 'init'){
                InfraredModule.destory();
                //console.log('释放了列表页的红外读头 状态:'+InfraredModule.getState());
            }
            
            if(this.infraredListener){
                //console.log('释放了列表页的红外监听');
                this.infraredListener.remove();
            }
        }
    }

    onBackClicked = () => {
        this.props.navigation.navigate('Main');
        this.props.navigation.state.params.callBack();
        return true;
    }

    showMenu = () => {
        Animated.timing(                            // 随时间变化而执行的动画类型
            this.state.fadeAnim,                      // 动画中的变量值
            {
              toValue: 0,                             
            }
        ).start();   
    }

    closeMenu = () => {
        Animated.timing(                            // 随时间变化而执行的动画类型
            this.state.fadeAnim,                      // 动画中的变量值
            {
              toValue: -(getScreenWidth() / 2),                             
            }
        ).start();  
    }

    main = () => {
        this.props.navigation.navigate('Main');
        this.props.navigation.state.params.callBack();
        this.closeMenu();
    }

    search = () => {
        
        // if(this.state.tab == 0){
        //     this.closeMenu();
        // }else{
        //     this.scrollableTabView.goToPage(0)
        // }
        this.scrollableTabView.goToPage(0)
        this.closeMenu();
    }

    initCard = () => {
        
        // if(this.state.tab == 1){
        //     this.closeMenu();
        // }else{
        //     this.scrollableTabView.goToPage(1)
        // }
        this.scrollableTabView.goToPage(1)
        this.closeMenu();
    }

    locationChange = () => {
        
        // if(this.state.tab == 2){
        //     this.closeMenu();
        // }else{
        //     this.scrollableTabView.goToPage(2)
        // }
        // this.scrollableTabView.goToPage(2)
        // this.closeMenu();
        this.props.navigation.navigate('LocationChange');
    }
    move = () => {
        
        // if(this.state.tab == 2){
        //     this.closeMenu();
        // }else{
        //     this.scrollableTabView.goToPage(2)
        // }
        // this.scrollableTabView.goToPage(2)
        // this.closeMenu();
        this.props.navigation.navigate('AddMove');
    }

    supplement = () => {
        this.scrollableTabView.goToPage(2)
        this.closeMenu();
    }

    install =() => {
        this.props.navigation.navigate('InstallEquipment',{
            callBack: () => {
                this.props.navigation.state.params.callBack();
            } 
        });
        this.closeMenu();
    }

    assetPay =() => {
        this.props.navigation.navigate('AssetPay',{
            callBack: () => {
                this.props.navigation.state.params.callBack();
            } 
        });
        this.closeMenu();
    }

    inventory = () => {
        this.props.navigation.navigate('Inventory',{
            callBack: () => {
                this.props.navigation.state.params.callBack();
            }        
        });
        this.closeMenu();
    }

    scan = (code) => {
        if(this.state.tab === 0){
            DeviceEventEmitter.emit('searchScan', code);
            return;
        }else if(this.state.tab === 1){
            DeviceEventEmitter.emit('initScan', code);
            return;
        }else if(this.state.tab === 2){
            DeviceEventEmitter.emit('supplementScan', code);
            return;
        }else if(this.state.tab === 2){
            DeviceEventEmitter.emit('moveScan', code);
            return;
        }
    }
    
    changeTab = (index, from) => {
        if(index === 0 && index !== from){
            this.setKeyWord('');
            DeviceEventEmitter.emit('searchChange');
            return;
        }else if(index === 1 && index !== from){
            this.setKeyWord('');
            DeviceEventEmitter.emit('initChange');
            return;
        }else if(index === 2 && index !== from){
            this.setKeyWord('');
            DeviceEventEmitter.emit('supplementChange');
            return;
        }else if(index === 3 && index !== from){
            this.setKeyWord('');
            DeviceEventEmitter.emit('moveChange');
            return;
        }
    }

    submit = (text) => {
        if(this.state.tab === 0){
            DeviceEventEmitter.emit('searchSubmit', text);
            return;
        }else if(this.state.tab === 1){
            DeviceEventEmitter.emit('initSubmit', text);
            return;
        }else if(this.state.tab === 2){
            DeviceEventEmitter.emit('supplementSubmit', text);
            return;
        }else if(this.state.tab === 3){
            DeviceEventEmitter.emit('moveSubmit', text);
            return;
        }
    }

    setKeyWord = (keyWord) => {
        //console.log(keyWord);
        this.setState({
            keyWord: keyWord,
        })
    }

    infraredReceived(code) {
        //console.log(code[0])
        if(that.state.tab === 0){
            DeviceEventEmitter.emit('searchScan', code[0]);
            return;
        }else if(that.state.tab === 1){
            DeviceEventEmitter.emit('initScan', code[0]);
            return;
        }else if(that.state.tab === 2){
            DeviceEventEmitter.emit('supplementScan', code[0]);
            return;
        }else if(that.state.tab === 3){
            DeviceEventEmitter.emit('moveScan', code[0]);
            return;
        }
    }

    rfidInit(){
        if(DeviceInfo.getDeviceId() === 'rk30sdk'){
            // 红外测试
            //console.log('列表页的红外读头状态:'+InfraredModule.getState());
            InfraredModule.init();
            //console.log('列表页红外初始化完成')
            this.infraredListener = DeviceEventEmitter.addListener('onInfraredReveice', this.infraredReceived);
        }
    }

    render() {

        const { params } = this.props.navigation.state;
        const tab = params ? params.tab : 0; 
        const menus = params ? params.menus : 0; 
        return (
            <SafeAreaView style={styles.container}>
                <NavigationEvents onDidFocus={() => this.rfidInit() } onDidBlur={() => this.componentWillUnmount()}/>
                <HeaderBarWhite navigation={ this.props.navigation } tab={this.state.tab} keyWord={this.state.keyWord} setKeyWord={this.setKeyWord} menuClink={ () => this.showMenu()} scan= {this.scan} submit= {this.submit} />
                <ScrollableTabView
                    ref={(ref) => { this.scrollableTabView = ref; }}
                    style={{ marginTop: getPixel(7) }}
                    initialPage={ tab }
                    renderTabBar={() => <DefaultTabBar />}
                    tabBarActiveTextColor='#4A69DD'
                    tabBarInactiveTextColor='#333'
                    tabBarUnderlineStyle={[ menus.indexOf("信息补录")>-1?{width: getPixel(90),marginLeft: getPixel(20)}:{width: getPixel(120),marginLeft: getPixel(36)}, {backgroundColor: '#4A69DD', height: getPixel(2) }]}
                    tabBarTextStyle={{ fontSize: getPixel(15) }}
                    onChangeTab={({i,from}) => {
                       // if(i != from){
                            this.changeTab(i, from);
                        //}
                        this.setState({
                            tab: i,
                        });
                    }}
                >
                    <AssetList tabLabel='资产查询' navigation={ this.props.navigation } />
                    <AssetInit tabLabel='资产绑定' navigation={ this.props.navigation } />
                    {menus.indexOf("信息补录")>-1? <AssetInfoSupplement tabLabel='信息补录' navigation={ this.props.navigation } />:null}
                    {/* <AssetMove tabLabel='资产迁移' navigation={ this.props.navigation } /> */}
                </ScrollableTabView>
                <Animated.View style={[{ alignItems:'center', elevation: 4, left: this.state.fadeAnim, position: 'absolute',width:getScreenWidth() / 2, backgroundColor: '#FFF' }, Platform.OS == 'ios' ? { height: getScreenHeight() - getPixel(30), marginTop: getPixel(30)}:{ height: getScreenHeight()}]}>
                    <View style={{ width:getScreenWidth() / 2, alignItems:'flex-end', paddingTop: getPixel(10), paddingRight: getPixel(10) }}>
                        <TouchableOpacity onPress={() => this.closeMenu()}>
                        <Image source={ require('../images/close_menu.png')} style={{width: getPixel(25),height: getPixel(25)}} />
                        </TouchableOpacity>
                    </View>
                    <Image source={ require('../images/default_user.png')} style={{width: getPixel(70),height: getPixel(70), marginTop: getPixel(10)}} />
                    <Text style={{ color:'#333', marginTop: getPixel(0), textAlign:'center', fontSize:getPixel(20), height: getPixel(60), lineHeight: getPixel(60)}}>{global.variables.user.name}</Text>
                    <View style={{paddingLeft: getPixel(20), paddingRight: getPixel(20)}}>
                        <TouchableOpacity onPress={() => this.main()}> 
                            <View style={ styles.menu }>
                                <Image source={ require('../images/icon_home.png')} style={{width: getPixel(25),height: getPixel(25), marginTop: getPixel(3)}} />
                                <Text style={styles.menuText }>首页</Text>
                            </View>
                        </TouchableOpacity>

                        {menus.indexOf("资产查询")>-1?<TouchableOpacity onPress={() => this.search()}> 
                            <View style={ styles.menu }>
                                <Image source={ require('../images/icon_asset.png')} style={{width: getPixel(25),height: getPixel(25), marginTop: getPixel(3)}} />
                                <Text style={styles.menuText }>资产查询</Text>
                            </View>
                        </TouchableOpacity>:null}
                        {menus.indexOf("资产绑定")>-1?<TouchableOpacity onPress={() => this.initCard()}>
                            <View style={ styles.menu }>
                                <Image source={ require('../images/icon_bind.png')} style={{width: getPixel(25),height: getPixel(25), marginTop: getPixel(3)}} />
                                <Text style={styles.menuText }>资产绑定</Text>
                            </View>
                        </TouchableOpacity>:null}
                        {menus.indexOf("信息补录")>-1?<TouchableOpacity onPress={() => this.supplement()}>
                            <View style={ styles.menu }>
                                <Image source={ require('../images/icon_msg.png')} style={{width: getPixel(25),height: getPixel(25), marginTop: getPixel(3)}}/>
                                <Text style={styles.menuText }>信息补录</Text>
                            </View>
                        </TouchableOpacity>:null}
                        {menus.indexOf("资产装机")>-1?<TouchableOpacity onPress={() => this.install()}>
                            <View style={ styles.menu }>
                                <Image source={ require('../images/icon_equipment.png')} style={{width: getPixel(25),height: getPixel(25), marginTop: getPixel(3)}}/>
                                <Text style={styles.menuText }>资产装机</Text>
                            </View>
                        </TouchableOpacity>:null}
                        {menus.indexOf("资产交付")>-1?<TouchableOpacity onPress={() => this.assetPay()}>
                            <View style={ styles.menu }>
                                <Image source={ require('../images/icon_pay.png')} style={{width: getPixel(25),height: getPixel(25), marginTop: getPixel(3)}}/>
                                <Text style={styles.menuText }>资产交付</Text>
                            </View>
                        </TouchableOpacity>:null}
                        {menus.indexOf("资产盘点")>-1?<TouchableOpacity onPress={() => this.inventory()}> 
                            <View style={ styles.menu }>
                                <Image source={ require('../images/icon_inventory.png')} style={{width: getPixel(25),height: getPixel(25), marginTop: getPixel(3)}} />
                                <Text style={styles.menuText }>资产盘点</Text>
                            </View>
                        </TouchableOpacity>:null}
                        {menus.indexOf("批量变更")>-1?<TouchableOpacity onPress={() => this.move()}> 
                            <View style={ styles.menu }>
                                <Image source={ require('../images/icon_move.png')} style={{width: getPixel(25),height: getPixel(25), marginTop: getPixel(3)}} />
                                <Text style={styles.menuText }>批量变更</Text>
                            </View>
                        </TouchableOpacity>:null}
                        {menus.indexOf("位置迁移")>-1?<TouchableOpacity onPress={() => this.locationChange()}> 
                            <View style={ styles.menu }>
                                <Image source={ require('../images/icon_pos.png')} style={{width: getPixel(25),height: getPixel(25), marginTop: getPixel(3)}} />
                                <Text style={styles.menuText }>位置迁移</Text>
                            </View>
                        </TouchableOpacity>:null}
                        <TouchableOpacity style={[{height : 40,marginTop: getScreenHeight() - getPixel(600)},Platform.OS == 'ios' ? { marginTop: getScreenHeight() - getPixel(510) }:null]} onPress={() => this.logout()}> 
                            <View style={styles.logout}>
                                <Image source={ require('../images/logout.png')} style={{width: getPixel(25),height: getPixel(25), marginTop: getPixel(3)}} />
                                <Text style={[styles.menuText,{color:'#FFF',fontWeight:'bold'}] }>注销</Text>
                            </View>
                        </TouchableOpacity>
                    </View>
                </Animated.View>
            </SafeAreaView>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    menu: {
        height: getPixel(40),
        borderBottomColor: '#EEE',
        borderBottomWidth: 1,
        width: getScreenWidth() / 2 - getPixel(40),
        flexDirection:'row',
        alignItems: 'center',
    },
    menuText: {
        marginLeft: getPixel(10),
        height: getPixel(40),
        lineHeight: getPixel(40),
        color:'#666',
        fontSize: getPixel(16),
    },

});